package com.opennetexam.manager.bussinessservice;

import com.opennetexam.manager.dto.ExamineePlanInfo;
import com.opennetexam.manager.mapper.*;
import com.opennetexam.manager.common.OperationResult;
import com.opennetexam.manager.databasemodel.*;
import com.opennetexam.manager.dto.ExamineeAnswerDetailViewModel;
import com.opennetexam.manager.dto.ExamineeOperateLogDTO;
import com.opennetexam.manager.enums.ExamManagerState;
import com.opennetexam.manager.enums.ExamMode;
import com.opennetexam.manager.enums.OperationResultType;
import com.opennetexam.manager.utils.DateUtil;
import com.opennetexam.manager.utils.GsonUtil;
import com.opennetexam.manager.utils.PublicHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author 奶茶
 * Created on 2017/11/9.
 */
@Service(value = "examingService")
@Transactional(rollbackFor = RuntimeException.class)
public class ExamingService {

    @Autowired
    private ExamMoniterMapper examMoniterMapper;
    @Autowired
    private ExamineeAnswerDetailMapper examineeAnswerDetailMapper;

    /**
     * 根据考生编号 考试计划 场次 科目 计算考生考试剩余时长，保存并返回(随考)
     *
     * @return
     */
    public int saveExamineeRetainTime(ExamingMonitor examingMonitors, ExamPlanInfo examPlanInfo, ExamSubject subject, ExamineeArrange examineeArrange) {

        //如果是随考模式
        String startTime = ExamMode.freeExam.getPrefix().equals(examPlanInfo.getExamMode()) ? examingMonitors.getExamStartTime() : examineeArrange.getPlanBeginTime();
        //本场考试的总时长
        Integer timeLimits = subject.getTimeLimits();
        //计算已经进行的时长
        int timeDifference = DateUtil.getTimeDifference(new Date(), DateUtil.convertStringToDate(startTime)).intValue();
        //延迟时长
        Integer delayMinute = examingMonitors.getDelayMinute();
        //计算剩下的时长
        int retainTime = timeLimits * 60 + delayMinute * 60 - timeDifference;
        //如果计算得出数据是0或者负数  直接返回0
        if (retainTime <= 0) {
            examingMonitors.setRetainTime(0);
            examMoniterMapper.updateExamingMoniter(examingMonitors);
            return 0;
        } else {
            examingMonitors.setRetainTime(retainTime);
            examMoniterMapper.updateExamingMoniter(examingMonitors);
            return retainTime;
        }
    }

    /**
     * 保存试题作答结果
     *
     * @param examineeId 考生标识
     * @param answerList
     * @return
     */
    @Transactional(isolation = Isolation.SERIALIZABLE, rollbackFor = Exception.class)
    public OperationResult saveAnswer(String examineeId, List<ExamineeAnswerDetailViewModel> answerList) {

        OperationResult operationResult = new OperationResult();

        for (ExamineeAnswerDetailViewModel examineeAnswerDetailViewModel : answerList) {
            //生成新作答
            ExamineeAnswerDetail examineeAnswerDetail = new ExamineeAnswerDetail();
            examineeAnswerDetail.setExamineeId(examineeId);
            examineeAnswerDetail.setExamPaperID(examineeAnswerDetailViewModel.getExamPaperID());
            examineeAnswerDetail.setExamPaperItemId(examineeAnswerDetailViewModel.getExamPaperItemId());
            examineeAnswerDetail.setSequenceIndex(examineeAnswerDetailViewModel.getSequenceIndex());
            examineeAnswerDetail.setIsCompletion(examineeAnswerDetailViewModel.getIsCompletion());
            examineeAnswerDetail.setMarked(examineeAnswerDetailViewModel.getMarked());
            examineeAnswerDetail.setCreateTime(DateUtil.convertDateToString(new Date()));
            examineeAnswerDetail.setScore(new BigDecimal(0));
            String answerResult = GsonUtil.toJson(examineeAnswerDetailViewModel.getAnswerResults());
            if ("[\"\"]".equals(answerResult) || "[\" \"]".equals(answerResult) || "[\"undefined\"]".equals(answerResult) || "['']".equals(answerResult) || answerResult == null) {
                answerResult = "[]";
            }
            examineeAnswerDetail.setAnswerResults(answerResult);
            //保存考生作答明细
            examineeAnswerDetailMapper.addExamineeAnswerDetail(examineeAnswerDetail);
            return new OperationResult(OperationResultType.Success);
        }

        return operationResult;
    }

    /**
     * 提交后更改考试状态,交卷时间,结束时间
     *
     * @param appId          主办方标识
     * @param examPlanInfoId 计划标识
     * @param examSubjectId  科目标识
     * @param examineeId     考生标识
     * @param submitType     交卷类型：0未交卷；1考生自行交卷；2考生试卷导入；3系统自动交卷；4强制交卷
     * @return
     */
    public OperationResult submitPaper(ExamingMonitor examingMonitors, Integer examMode, String appId, String examPlanInfoId, String examSubjectId, String examineeId, Integer submitType) {

        if (examMode.equals(ExamMode.unifiedExam.getPrefix())) {
            examingMonitors = examMoniterMapper.findExamingMonitorsFirstOrDefault(appId, examPlanInfoId, examSubjectId, examineeId);
        }

        examingMonitors.setSubmitType(submitType.shortValue());
        examingMonitors.setSysState(ExamManagerState.Submited.getPrefix().shortValue());
        examingMonitors.setExamEndTime(DateUtil.convertDateToString(new Date()));
        //更新考试
        Integer result = examMoniterMapper.updateExamingMoniter(examingMonitors);
        if (result > 0) {
            return new OperationResult(OperationResultType.Success, "交卷成功", -1);
        } else {
            return new OperationResult(OperationResultType.Warning, "交卷失败", -1);
        }
    }
}
